package com.web.ShoppingDemo.util;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.stereotype.Component;

/**
 * 完成邮件的发送
 * 
 * @author THT
 * 
 */
@Component("emailUtil")
public class EmailUtilImpl implements EmailUtil {

	/* (non-Javadoc)
	 * @see com.web.ShoppingDemo.util.MessageUtil#sendMessage(java.lang.String, java.lang.String)
	 */
	@Override
	public void sendEmail(String address, String id) {
		Properties props = new Properties();
		Session session = null;
		Message message = null;
		Transport transport = null;
		try {
			// 登录邮件客户端
			props.setProperty("mail.transport.protocol", "smtp");
			session = Session.getDefaultInstance(props);
			// 设置debug模式设置发送信息
			session.setDebug(true);

			// 创建一封邮件对象
			message = new MimeMessage(session);
			// 写信
			message.setSubject("订单支付成功邮件!");
			message.setContent("订单"+id+"已经支付成功!", "text/html;charset=utf-8");
			// 发件人地址
			message.setFrom(new InternetAddress("soft03_test@sina.com"));

			transport = session.getTransport();
			// 邮件服务器的认证信息
			transport.connect("smtp.sina.com", "soft03_test", "soft03_test");
			// 收件人地址
			transport.sendMessage(message, new Address[] { new InternetAddress(
					address) });
		} catch (Exception e) {
			throw new RuntimeException("邮件发送异常!");
		} finally{
			try {
				transport.close();
			} catch (MessagingException e) {
				throw new RuntimeException();
			}
		}
	}
}
